
/**
 * 在数组查找是否有与给定数据一样的数据
 * @param {*} arr 要操作的数组
 * @param {*} key 数组里保存的数据
 * @param {*} val 要比较的数据
 */
function inArray(arr, key, val) {//inArray(foundDevices, 'deviceId', device.deviceId)
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

//字符串转Uint8Array
function str2ab1(str) {
  var bufView = new Uint8Array(str.length);// Uint8Array可换成其它
  for (var i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  console.log(bufView)
  console.log('00000-3')
  return bufView;
}

//字符串转ArrayBuffer
function str2ab(str) {
  var buf = new ArrayBuffer(str.length); // 每个字符占用2个字节
  var bufView = new Uint8Array(buf);// Uint8Array可换成其它
  for (var i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}
//宽字节字符串转ArrayBuffer
function str2ab2(str) {
  var buf = new ArrayBuffer(str.length * 2); // 每个字符占用2个字节
  var bufView = new Uint8Array(buf);// Uint8Array可换成其它
  for (var i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

Page({
  data: {
    devices: [],
    connected: false,
    chs: [],
    shuJuShuRu: "",
    shuJuShuRuPanDuan: false
  },
  shuJuShuRuH: function (e) {
    if (e.detail.value != "" && e.detail.value.length <= 20) {
      this.setData({
        shuJuShuRu: e.detail.value,
        shuJuShuRuPanDuan: true
      })
    }
  },
  //开始扫描 
  openBluetoothAdapter() {
    //初始化蓝牙模块
    console.log('kai shi sao miao 0001')
    wx.openBluetoothAdapter({
      success: (res) => { //接口调用成功的回调函数
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => { //接口调用失败的回调函数
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },
  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        console.log('getBluetoothAdapterState', res)
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()
        }
      }
    })
  },
  /**初始化蓝牙模块,接口调用成功的回调函数 */
  startBluetoothDevicesDiscovery() {
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({ //开始搜寻附近的蓝牙外围设备
      allowDuplicatesKey: true, //是否允许重复上报同一设备
      success: (res) => { //接口调用成功的回调函数
        console.log('0000_startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
    })
  },
  stopBluetoothDevicesDiscovery() {//停止搜寻附近的蓝牙外围设备
    wx.stopBluetoothDevicesDiscovery()
  },
  /**开始搜寻附近的蓝牙外围设备成功的回调 */
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {//搜索到新设备的事件的监听函数
      res.devices.forEach(device => {//对数组中的每个元素执行指定的操作
        if (!device.name && !device.localName) {
          return
        }
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}//这里可以指代this.data
        if (idx === -1) {
          /**
           * 将 `device` 对象添加到 `foundDevices` 数组中，并将其索引设置为 `foundDevices.length`,就是给数组的最后再增加一个成员
           * `device` 对象将作为数组的最后一个元素添加到 `foundDevices` 数组中。
           */
          data[`devices[${foundDevices.length}]`] = device
        } else {
          /**如果 `foundDevices` 数组中已经存在一个索引为 `foundDevices.length` 的元素，那么这个元素将被更新为 `device` 对象 */
          data[`devices[${idx}]`] = device
        }
        this.setData(data)//更新data
      })
    })
  },
  createBLEConnection(e) {
    console.log('0001')
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    wx.createBLEConnection({//连接蓝牙低功耗设备
      deviceId,//蓝牙设备 id
      success: (res) => {//接口调用成功的回调函数
        this.setData({
          connected: true,
          name,
          deviceId,
        })
        this.getBLEDeviceServices(deviceId)
      }
    })
    this.stopBluetoothDevicesDiscovery()
  },
  closeBLEConnection() {
    console.log('0002')
    wx.closeBLEConnection({//断开与蓝牙低功耗设备的连接。
      deviceId: this.data.deviceId//蓝牙设备 id
    })
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
    })
  },
  getBLEDeviceServices(deviceId) {
    console.log('0003')
    wx.getBLEDeviceServices({//获取蓝牙低功耗设备所有服务 (service)
      deviceId,//蓝牙设备 id。需要已经通过 wx.createBLEConnection 建立连接
      success: (res) => {//接口调用成功的回调函数
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            return
          }
        }
      }
    })
  },
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    console.log('0004')
    wx.getBLEDeviceCharacteristics({//获取蓝牙低功耗设备某个服务中所有特征 (characteristic)。
      deviceId,//蓝牙设备 id。需要已经通过 wx.createBLEConnection 建立连接
      serviceId,//蓝牙服务 UUID。需要先调用 wx.getBLEDeviceServices 获取
      success: (res) => {//回调函数
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            this.setData({
              canWrite: true
            })
            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid
            //this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    // 操作之前先监听，保证第一时间获取数据
    wx.onBLECharacteristicValueChange((characteristic) => {
      console.log('0005')
      const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
      const data = {}
      if (idx === -1) {
        data[`chs[${this.data.chs.length}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      } else {
        data[`chs[${idx}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      }
      // data[`chs[${this.data.chs.length}]`] = {
      //   uuid: characteristic.characteristicId,
      //   value: ab2hex(characteristic.value)
      // }
      this.setData(data)
    })
  },

  writeBLECharacteristicValue() {//向蓝牙低功耗设备特征值中写入二进制数据
    console.log('0006')
    //var buffer = stringToBytes("lokj,112.9089")
    if (this.data.shuJuShuRuPanDuan) {
      // 字符 转 ArrayBuffer
      let arrayBuffer1 = str2ab(this.data.shuJuShuRu);
      // 字符 转 Uint8Array
      let uint8Array = str2ab1(this.data.shuJuShuRu);
      console.log(uint8Array);
      // Uint8Array 转 ArrayBuffer
      let arrayBuffer = uint8Array.buffer
      console.log(arrayBuffer);

      wx.writeBLECharacteristicValue({//向蓝牙低功耗设备特征值中写入二进制数据
        deviceId: this._deviceId,//蓝牙设备 id
        serviceId: this._serviceId,//蓝牙特征对应服务的 UUID
        characteristicId: this._characteristicId,//蓝牙特征的 UUID
        value: arrayBuffer1,//写入的数据
      })
    }
    // 向蓝牙设备发送一个0x00的16进制数据
    
    //let buffer = new ArrayBuffer(1)

  },
  closeBluetoothAdapter() {//关闭蓝牙模块。
    wx.closeBluetoothAdapter()//关闭蓝牙模块。
    this._discoveryStarted = false
  },
})